<template>
  <div class="app-container">
    <!-- 编辑规则弹窗 -->
    <el-dialog
      :title="'编辑规则'"
      :visible.sync="ruleOpen"
      append-to-body
      width="500px"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="规则编号" prop="code">
          <el-input v-model="ruleForm.code" placeholder="请输入规则编号" />
        </el-form-item>
        <el-form-item label="生效时间类型" prop="takeEffectType">
          <el-select
            v-model="ruleForm.takeEffectType"
            placeholder="请选择生效时间类型"
          >
            <el-option
              v-for="dict in dict.type.iot_rule_time_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="生效时间范围"
          prop="timeRange"
          v-if="ruleForm.takeEffectType === 'appoint'"
        >
          <div style="display: flex; align-items: center">
            <el-time-picker
              is-range
              v-model="takeEffectTimeForm"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
              format="HH:mm"
              value-format="HH:mm"
              default-time="00:00"
            >
            </el-time-picker>
          </div>
        </el-form-item>
        <el-form-item
          label="生效周期"
          prop="takeEffectWeeks"
          v-if="ruleForm.takeEffectType === 'appoint'"
        >
          <el-checkbox-group v-model="ruleForm.takeEffectWeeks">
            <el-checkbox label="周一">周一</el-checkbox>
            <el-checkbox label="周二">周二</el-checkbox>
            <el-checkbox label="周三">周三</el-checkbox>
            <el-checkbox label="周四">周四</el-checkbox>
            <el-checkbox label="周五">周五</el-checkbox>
            <el-checkbox label="周六">周六</el-checkbox>
            <el-checkbox label="周日">周日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          label="生效日期"
          prop="effectiveDate"
          v-if="ruleForm.takeEffectType === 'appoint'"
        >
          <el-date-picker
            v-model="effectiveDateForm"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择日期范围"
          />
        </el-form-item>
        <el-form-item label="触发类型" prop="triggerType">
          <el-select
            v-model="ruleForm.triggerType"
            placeholder="请选择触发类型"
          >
            <el-option
              v-for="dict in dict.type.iot_rule_trigger_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规则描述" prop="remark">
          <el-input
            v-model="ruleForm.remark"
            type="textarea"
            placeholder="请输入规则描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRuleForm">确 定</el-button>
        <el-button @click="cancelRule">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 规则信息卡片 -->
    <el-card class="box-card mb20">
      <div slot="header" class="clearfix">
        <span>规则信息</span>
        <el-button
          style="float: right; margin-left: 10px"
          type="primary"
          icon="el-icon-edit"
          size="mini"
          @click="handleEditRule"
          >编辑规则</el-button
        >
      </div>
      <el-form ref="form" :model="form" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="规则名称" prop="name">
              <span>{{ form.name }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规则编号" prop="code">
              <span>{{ form.code }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="触发类型" prop="triggerType">
              <dict-tag
                :options="dict.type.iot_rule_trigger_type"
                :value="form.triggerType"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生效时间类型" prop="takeEffectType">
              <dict-tag
                :options="dict.type.iot_rule_time_type"
                :value="form.takeEffectType"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="运行状态" prop="runState">
              <dict-tag :options="dict.type.iot_state" :value="form.runState" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间" prop="createTime">
              <span>{{ form.createTime }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.takeEffectType === 'appoint'">
          <el-col :span="8">
            <el-form-item label="生效周期" prop="effectiveDate">
              <span>{{ form.effectiveDate }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生效时间范围" prop="takeEffectTime">
              <span>{{ form.takeEffectTime }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="生效周期" prop="takeEffectWeeks">
              <span>{{ form.takeEffectWeeks }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="规则描述" prop="remark">
              <span>{{ form.remark }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 触发器信息卡片 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>触发器信息</span>
        <el-button
          v-if="!triggerForm.triggerId"
          style="float: right"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAddTrigger"
          >创建触发器</el-button
        >
        <el-button
          v-if="triggerForm.triggerId"
          style="float: right; margin-left: 10px"
          type="primary"
          icon="el-icon-edit"
          size="mini"
          @click="handleEditTrigger"
          >编辑触发器</el-button
        >
        <el-button
          v-if="triggerForm.triggerId"
          style="float: right"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="handleDeleteTrigger"
          >删除触发器</el-button
        >
      </div>
      <div v-if="triggerForm.triggerId">
        <el-form :model="triggerForm" label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="触发器条件" prop="triggerCondition">
                <span>{{
                  triggerForm.triggerCondition === "or" ? "任意一个" : "全部"
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否抑制" prop="isRestrain">
                <span>{{ triggerForm.isRestrain === "0" ? "否" : "是" }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" v-if="triggerForm.isRestrain === '1'">
              <el-form-item label="抑制时间" prop="intervalTime">
                <span>{{ triggerForm.intervalTime }}分钟</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="会话时间" prop="dataTime">
                <span>{{ triggerForm.dataTime }}秒</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="重复次数" prop="repeatNum">
                <span>{{ triggerForm.repeatNum }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="触发项类型" prop="termType">
                <span>{{
                  triggerForm.termType === "property"
                    ? "属性触发"
                    : triggerForm.termType === "event"
                    ? "事件触发"
                    : "设备上下线"
                }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="触发器描述" prop="remark">
                <span>{{ triggerForm.remark }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- 触发项列表 -->
        <div class="trigger-terms-list">
          <div class="list-header">
            <span>触发项列表</span>
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAddTerm"
              >添加触发项</el-button
            >
          </div>
          <el-row :gutter="20">
            <el-col
              :span="8"
              v-for="(item, index) in termList"
              :key="index"
              class="mb20"
            >
              <el-card shadow="hover" class="term-card">
                <div class="term-card-content">
                  <div class="term-info">
                    <p>
                      <span class="label">产品名称：</span
                      >{{ item.productName }}
                    </p>
                    <p>
                      <span class="label">设备名称：</span>{{ item.deviceName }}
                    </p>
                    <p>
                      <span class="label">属性名称：</span
                      >{{ item.attributeName }}
                    </p>
                    <p>
                      <span class="label">比较运算符：</span>
                      <span>{{
                        getComparisonOperatorLabel(item.comparisonOperator)
                      }}</span>
                    </p>
                    <p>
                      <span class="label">属性值：</span>
                      <span v-if="item.comparisonOperator === 'between'"
                        >{{ item.valueMin }} - {{ item.valueMax }}</span
                      >
                      <span v-else-if="item.comparisonOperator === 'in'">{{
                        item.valueList
                      }}</span>
                      <span v-else>{{ item.valueMax }}</span>
                    </p>
                  </div>
                  <div class="term-actions">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="handleEditTerm(item)"
                      >修改</el-button
                    >
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDeleteTerm(item)"
                      >删除</el-button
                    >
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
      <div v-else class="empty-block">
        <span class="empty-text">暂无触发器，请点击右上角创建</span>
      </div>
    </el-card>

    <!-- 创建触发器弹窗 -->
    <el-dialog
      :title="'创建触发器'"
      :visible.sync="triggerOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="triggerForm"
        :model="triggerForm"
        :rules="triggerRules"
        label-width="120px"
      >
        <el-form-item label="触发器描述" prop="remark">
          <el-input
            v-model="triggerForm.remark"
            type="textarea"
            placeholder="请输入触发器描述"
          />
        </el-form-item>
        <el-form-item label="触发器条件" prop="triggerCondition">
          <el-radio-group v-model="triggerForm.triggerCondition">
            <el-radio label="or">任意一个</el-radio>
            <el-radio label="and">全部</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否抑制" prop="isRestrain">
          <el-radio-group v-model="triggerForm.isRestrain">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="抑制时间"
          prop="intervalTime"
          v-if="triggerForm.isRestrain == '1'"
        >
          <el-input-number
            v-model="triggerForm.intervalTime"
            :min="0"
            placeholder="请输入间隔时间"
          />
          <span class="unit-label">分钟</span>
        </el-form-item>
        <el-form-item label="会话时间" prop="dataTime">
          <el-input-number
            v-model="triggerForm.dataTime"
            :min="0"
            placeholder="请输入数据时效"
          />
          <span class="unit-label">秒</span>
        </el-form-item>
        <el-form-item label="重复次数" prop="repeatNum">
          <el-input-number
            v-model="triggerForm.repeatNum"
            :min="1"
            placeholder="请输入重复次数"
          />
        </el-form-item>
        <el-form-item label="触发项类型" prop="termType">
          <el-select
            v-model="triggerForm.termType"
            placeholder="请选择触发项类型"
          >
            <el-option label="属性触发" value="property" />
            <el-option label="事件触发" value="event" />
            <el-option label="设备上下线" value="online" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTriggerForm">确 定</el-button>
        <el-button @click="cancelTrigger">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 触发项弹窗 -->
    <el-dialog
      :title="termTitle"
      :visible.sync="termOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="termForm"
        :model="termForm"
        :rules="termRules"
        label-width="120px"
      >
        <el-form-item label="产品" prop="productId">
          <el-select
            v-model="termForm.productId"
            placeholder="请选择产品"
            @change="handleProductChange"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备" prop="deviceId">
          <el-select
            v-model="termForm.deviceId"
            placeholder="请选择设备"
            :disabled="!termForm.productId"
          >
            <el-option
              v-for="item in deviceOptions"
              :key="item.deviceId"
              :label="item.deviceName"
              :value="item.deviceId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="属性" prop="attributeId">
          <el-select
            v-model="termForm.attributeId"
            placeholder="请选择属性"
            :disabled="!termForm.productId"
          >
            <el-option
              v-for="item in attributeOptions"
              :key="item.attributeId"
              :label="item.attributeName"
              :value="item.attributeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="比较运算符" prop="comparisonOperator">
          <el-select
            v-model="termForm.comparisonOperator"
            placeholder="请选择对比条件"
          >
            <el-option
              v-for="dict in dict.type.iot_comparison_operator"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="属性值"
          prop="valueMax"
          v-if="
            termForm.comparisonOperator !== 'range' &&
            termForm.comparisonOperator !== 'contain'
          "
        >
          <el-input v-model="termForm.valueMax" placeholder="请输入属性值" />
        </el-form-item>
        <el-form-item
          label="最小值"
          prop="valueMin"
          v-if="termForm.comparisonOperator === 'range'"
        >
          <el-input v-model="termForm.valueMin" placeholder="请输入最小值" />
        </el-form-item>
        <el-form-item
          label="最大值"
          prop="valueMax"
          v-if="termForm.comparisonOperator === 'range'"
        >
          <el-input v-model="termForm.valueMax" placeholder="请输入最大值" />
        </el-form-item>
        <el-form-item
          label="值集合"
          prop="valueList"
          v-if="termForm.comparisonOperator === 'contain'"
        >
          <el-input
            v-model="termForm.valueList"
            type="textarea"
            placeholder="请输入值集合，多个值用逗号分隔"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTermForm">确 定</el-button>
        <el-button @click="cancelTerm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.trigger-terms-list {
  margin-top: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.empty-block {
  padding: 32px 0;
  text-align: center;
  color: #909399;
}

.mb20 {
  margin-bottom: 20px;
}

.term-card {
  height: 100%;
}

.term-card-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.term-info {
  flex: 1;
}

.term-info p {
  margin: 8px 0;
  line-height: 1.5;
}

.term-info .label {
  font-weight: bold;
  color: #606266;
}

.term-actions {
  margin-top: 15px;
  text-align: right;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}
</style>

<script>
import { getRule, updateRule } from "@/api/system/iot/rule";
import {
  addTrigger,
  getTriggerByRule,
  updateTrigger,
} from "@/api/system/iot/trigger";
import {
  listTerm,
  getTerm,
  delTerm,
  addTerm,
  updateTerm,
} from "@/api/system/iot/term";
import { findProductConfigList } from "@/api/system/iot/product";
import { listDevice } from "@/api/system/iot/device";
import { listAttribute } from "@/api/system/iot/attribute";

export default {
  dicts: [
    "sys_normal_disable",
    "iot_rule_status",
    "iot_rule_time_type",
    "iot_state",
    "iot_rule_trigger_type",
    "iot_comparison_operator",
  ],
  data() {
    return {
      effectiveDateForm: [],
      takeEffectTimeForm: [],
      // 编辑规则弹窗
      ruleOpen: false,
      // 编辑规则表单
      ruleForm: {
        ruleId: undefined,
        name: undefined,
        code: undefined,
        takeEffectType: undefined,
        takeEffectTime: undefined,
        takeEffectWeeks: [],
        effectiveDate: undefined,
        triggerType: undefined,
        remark: undefined,
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "规则名称不能为空", trigger: "blur" },
        ],
        code: [
          { required: true, message: "规则编号不能为空", trigger: "blur" },
        ],
        takeEffectType: [
          { required: true, message: "请选择生效时间类型", trigger: "change" },
        ],
        triggerType: [
          { required: true, message: "请选择触发类型", trigger: "change" },
        ],
      },
      triggerOpen: false,
      termOpen: false,
      termTitle: "",
      // 规则表单对象
      form: {},
      // 触发器表单对象
      termList: [],
      // 触发项表单对象
      termForm: {
        termId: undefined,
        triggerId: undefined,
        productId: undefined,
        deviceId: undefined,
        attributeId: undefined,
        attributeName: undefined,
        comparisonOperator: undefined,
        valueMax: undefined,
        valueMin: undefined,
        valueList: undefined,
      },
      // 产品列表
      productOptions: [],
      // 设备列表
      deviceOptions: [],
      // 属性列表
      attributeOptions: [],
      // 触发项表单校验
      termRules: {
        productId: [
          { required: true, message: "产品ID不能为空", trigger: "blur" },
        ],
        deviceId: [
          { required: true, message: "设备ID不能为空", trigger: "blur" },
        ],
        attributeId: [
          { required: true, message: "属性ID不能为空", trigger: "blur" },
        ],
        attributeName: [
          { required: true, message: "属性名称不能为空", trigger: "blur" },
        ],
        comparisonOperator: [
          { required: true, message: "对比条件不能为空", trigger: "change" },
        ],
        valueMax: [
          { required: true, message: "属性值不能为空", trigger: "blur" },
        ],
      },
      // 触发器表单对象
      triggerForm: {
        ruleId: "",
        remark: "",
        triggerCondition: "or",
        isRestrain: "0",
        dataTime: 0,
        repeatNum: 0,
        intervalTime: 0,
        termType: "",
      },
      // 表单校验
      triggerRules: {
        remark: [
          { required: true, message: "触发器描述不能为空", trigger: "blur" },
        ],
        triggerCondition: [
          { required: true, message: "请选择触发器条件", trigger: "change" },
        ],
        isRestrain: [
          { required: true, message: "请选择是否抑制", trigger: "change" },
        ],
        dataTime: [
          { required: true, message: "请输入数据时效", trigger: "blur" },
        ],
        repeatNum: [
          { required: true, message: "请输入重复次数", trigger: "blur" },
          {
            type: "number",
            min: 1,
            message: "重复次数不能小于1",
            trigger: "blur",
          },
        ],
        intervalTime: [
          { required: true, message: "请输入间隔时间", trigger: "blur" },
        ],
        termType: [
          { required: true, message: "请选择触发项类型", trigger: "change" },
        ],
      },
    };
  },
  created() {
    const ruleId = this.$route.params.ruleId;
    this.getRuleDetail(ruleId);
  },
  computed: {
    comparisonOperatorOptions() {
      return this.dict.type.iot_comparison_operator;
    },
  },
  methods: {
    getComparisonOperatorLabel(value) {
      const option = this.comparisonOperatorOptions.find(
        (item) => item.value === value
      );
      return option ? option.label : value;
    },
    /** 查询规则详细 */
    getRuleDetail(ruleId) {
      getRule(ruleId).then((response) => {
        this.form = response.data;
        // 如果存在触发器，获取触发器详情
        if (response.data.ruleId) {
          this.getTriggersInfo(response.data.ruleId);
        }
      });
    },
    /** 获取触发器详情 */
    getTriggersInfo(ruleId) {
      getTriggerByRule(ruleId).then((response) => {
        this.triggerForm = response.data;
        if (this.triggerForm.triggerId) {
          this.getTermList(this.triggerForm.triggerId);
        }
      });
    },
    /** 获取触发项列表 */
    getTermList(triggerId) {
      listTerm({ triggerId: triggerId }).then((response) => {
        this.termList = response.rows;
      });
    },
    /** 取消按钮 */
    cancelTerm() {
      this.termOpen = false;
      this.resetTermForm();
    },
    /** 表单重置 */
    resetTermForm() {
      this.termForm = {
        termId: undefined,
        triggerId: undefined,
        productId: undefined,
        deviceId: undefined,
        property: undefined,
        propertyName: undefined,
        expression: undefined,
        valueMax: undefined,
        valueMin: undefined,
        valueList: undefined,
      };
      this.$refs["termForm"] && this.$refs["termForm"].resetFields();
    },
    /** 新增触发项按钮操作 */
    handleAddTerm() {
      this.resetTermForm();
      this.termForm.triggerId = this.triggerForm.triggerId;
      this.termOpen = true;
      this.termTitle = "添加触发项";
      // 加载产品列表
      this.loadProductOptions();
    },

    /** 加载产品列表 */
    loadProductOptions() {
      findProductConfigList().then((response) => {
        this.productOptions = response.data;
      });
    },

    /** 产品选择变更处理 */
    handleProductChange(productId) {
      this.termForm.deviceId = undefined;
      this.termForm.property = undefined;
      this.termForm.propertyName = undefined;
      this.deviceOptions = [];
      this.attributeOptions = [];

      if (productId) {
        // 加载设备列表
        listDevice({ productId: productId }).then((response) => {
          this.deviceOptions = response.rows;
        });
        // 加载属性列表
        listAttribute({ productId: productId }).then((response) => {
          this.attributeOptions = response.rows;
        });
      }
    },

    /** 修改触发项按钮操作 */
    handleEditTerm(row) {
      this.resetTermForm();
      // 先加载产品列表
      this.loadProductOptions();
      getTerm(row.termId).then((response) => {
        // 先调用handleProductChange加载设备和属性列表
        if (response.data.productId) {
          this.handleProductChange(response.data.productId);
        }
        // 等待一小段时间确保列表加载完成
        setTimeout(() => {
          this.termForm = response.data;
          this.termOpen = true;
          this.termTitle = "修改触发项";
        }, 100);
      });
    },
    /** 提交触发项表单 */
    submitTermForm() {
      this.$refs["termForm"].validate((valid) => {
        if (valid) {
          if (this.termForm.termId) {
            updateTerm(this.termForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.termOpen = false;
              this.getTermList(this.triggerForm.triggerId);
            });
          } else {
            addTerm(this.termForm).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.termOpen = false;
              this.getTermList(this.triggerForm.triggerId);
            });
          }
        }
      });
    },
    /** 删除触发项按钮操作 */
    handleDeleteTerm(row) {
      this.$modal
        .confirm('是否确认删除触发项编号为"' + row.termId + '"的数据项？')
        .then(() => {
          delTerm(row.termId).then(() => {
            this.$modal.msgSuccess("删除成功");
            this.getTermList(this.triggerForm.triggerId);
          });
        })
        .catch(() => {});
    },
    handleAddTrigger() {
      this.triggerForm = {
        ruleId: this.form.ruleId,
        triggerName: "",
        remark: "",
        triggerCondition: "or",
        isRestrain: "0",
        dataTime: 0,
        repeatNum: 1,
        intervalTime: 0,
        termType: "",
      };
      this.triggerOpen = true;
    },
    cancelTrigger() {
      this.triggerOpen = false;
      this.triggerForm = {};
      this.getTriggersInfo(this.form.ruleId);
    },
    submitTriggerForm() {
      this.$refs["triggerForm"].validate((valid) => {
        if (valid) {
          if (this.triggerForm.triggerId) {
            updateTrigger(this.triggerForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.triggerOpen = false;
              this.getTriggersInfo(this.triggerForm.ruleId);
            });
          } else {
            addTrigger(this.triggerForm).then((response) => {
              this.$modal.msgSuccess("创建成功");
              this.triggerOpen = false;
              this.getTriggersInfo(response.data.triggerId);
            });
          }
        }
      });
    },
    /** 编辑规则按钮操作 */
    handleEditRule() {
      this.ruleForm = {
        ...this.form,
        takeEffectWeeks: this.form.takeEffectWeeks
          ? this.form.takeEffectWeeks.split(",")
          : [],
      };
      // 解析生效时间范围
      if (this.form.takeEffectTime) {
        const [start, end] = this.form.takeEffectTime.split("至");
        this.takeEffectTimeForm = [start, end];
      } else {
        this.takeEffectTimeForm = ["00:00", "0:00"];
      }
      // 解析生效日期范围
      if (this.form.effectiveDate) {
        const [startDate, endDate] = this.form.effectiveDate.split("至");
        this.effectiveDateForm = [startDate, endDate];
      }
      this.ruleOpen = true;
    },
    // 取消按钮
    cancelRule() {
      this.ruleOpen = false;
      this.resetRuleForm();
    },
    // 表单重置
    resetRuleForm() {
      this.ruleForm = {
        ruleId: undefined,
        name: undefined,
        code: undefined,
        takeEffectType: undefined,
        startTime: undefined,
        endTime: undefined,
        takeEffectWeeks: [],
        effectiveDate: [],
        triggerType: undefined,
        remark: undefined,
      };
      this.$refs["ruleForm"] && this.$refs["ruleForm"].resetFields();
    },
    // 提交按钮
    submitRuleForm() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          // 格式化生效时间范围
          if (this.takeEffectTimeForm && this.takeEffectTimeForm.length === 2) {
            const startTime = this.takeEffectTimeForm[0];
            const endTime = this.takeEffectTimeForm[1];
            this.ruleForm.takeEffectTime = `${startTime}至${endTime}`;
          }

          // 格式化生效日期范围
          if (this.effectiveDateForm && this.effectiveDateForm.length === 2) {
            const startDate = this.effectiveDateForm[0];
            const endDate = this.effectiveDateForm[1];
            this.ruleForm.effectiveDate = `${startDate}至${endDate}`;
          }

          // 将数组转换为逗号分隔的字符串
          if (
            this.ruleForm.takeEffectWeeks &&
            Array.isArray(this.ruleForm.takeEffectWeeks)
          ) {
            this.ruleForm.takeEffectWeeks =
              this.ruleForm.takeEffectWeeks.join(",");
          }

          updateRule(this.ruleForm).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.ruleOpen = false;
            this.getRuleDetail(this.ruleForm.ruleId);
          });
        }
      });
    },

    /** 编辑触发器按钮操作 */
    handleEditTrigger() {
      this.triggerForm.ruleId = this.form.ruleId;
      this.triggerOpen = true;
    },
    /** 删除触发器按钮操作 */
    handleDeleteTrigger() {
      this.$modal
        .confirm("是否确认删除该触发器？")
        .then(() => {
          delTrigger(this.triggerForm.triggerId).then(() => {
            this.$modal.msgSuccess("删除成功");
            this.triggerForm = {};
            this.termList = [];
          });
        })
        .catch(() => {});
    },
  },
};
</script>
